# -*- coding: utf-8 -*-
import locale

from django.utils import datetime_safe
from django import forms
from django.forms.widgets import Input
from django.conf import settings
from django.utils.safestring import mark_safe

DEFAULT_DATE_INPUT_FORMATS = (
    '%d/%m/%Y',
)

class BRDateInput(Input):
    input_type = 'text'
    format = '%d/%m/%Y'     # '25/10/2006'
    
    class Media:
        js = (
              settings.ADMIN_MEDIA_PREFIX+'jquery/jquery.maskedinput.js',
        )
    
    def __init__(self, attrs=None, format=None):
        super(BRDateInput, self).__init__(attrs)
        if format:
            self.format = format

    def _format_value(self, value):
        if value is None:
            return ''
        elif hasattr(value, 'strftime'):
            value = datetime_safe.new_date(value)
            return value.strftime(self.format)
        return value

    def render(self, name, value, attrs=None):
        value = self._format_value(value)
        rendered =  super(BRDateInput, self).render(name, value, attrs)
        return rendered + mark_safe(u'''
            <script type="text/javascript">
                $('document').ready(function(){
                    $('#id_%s').mask('99/99/9999')
                })
            </script>
        ''' % name)

    def _has_changed(self, initial, data):
        return super(BRDateInput, self)._has_changed(self._format_value(initial), data)

class DateFieldBR(forms.DateField):
    widget = BRDateInput
    def __init__(self, input_formats=None, *args, **kwargs):
        super(DateFieldBR, self).__init__(*args, **kwargs)
        self.input_formats = input_formats or DEFAULT_DATE_INPUT_FORMATS
